
/*
    死锁的避免
 */
public class lock2 {
    //将嵌套改为并行，可避免死锁
    public static void main(String[] args) {
        Object locker1 = new Object();
        Object locker2 = new Object();
        Thread t1 = new Thread(()->{
            synchronized (locker1){
                try {
                    //这里的sleep很有必要，以免t1执行过快造成死锁失败
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            synchronized (locker2){
                System.out.println("线程1加锁成功");
            }
        });
        Thread t2 = new Thread(()->{
            synchronized (locker2){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            synchronized (locker1){
                System.out.println("线程2加锁成功");
            }
        });
        t1.start();
        t2.start();
    }

    //死锁的演示(此处出现了嵌套加锁造成的死锁)
    public static void main1(String[] args) {
        Object locker1 = new Object();
        Object locker2 = new Object();
        Thread t1 = new Thread(()->{
            synchronized (locker1){
                try {
                    //这里的sleep很有必要，以免t1执行过快造成死锁失败
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (locker2){
                    System.out.println("线程1加锁成功");
                }
            }
        });
        Thread t2 = new Thread(()->{
            synchronized (locker2){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (locker1){
                    System.out.println("线程2加锁成功");
                }
            }
        });
        t1.start();
        t2.start();
    }
}
